import axios from "axios";
import store from "@/store";
import router from "@/router";
import { removeToken } from "./auth";
// 基准路径
// const baseURL = '/dev-api'
const baseURL = process.env.VUE_APP_BASE_API;

// 生成axios实例
const instance = axios.create({
  baseURL: baseURL,
});

// -------------------------------- 响应拦截器去除外层data
instance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    return response.data;
  },
  (err) => {
    if (err.response.status === 401 && err.response.data.code === 10002) {
      store.commit("user/SET_TOKEN", "");
      store.commit("user/upDateUserInfo", null);
      removeToken();
      router.push("/login");
    }
    // 对响应错误做点什么
    return Promise.reject(err);
  }
);

// --------------------------------- 添加请求拦截器,添加token
instance.interceptors.request.use(
  (config) => {
    const token = store.getters.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 导出 封装通用的接口函数
// 按照这种方式封装，无论那种请求方式,都使用data传参
export default (option) => {
  let key = null;
  if (option.method) {
    key = option.method.toUpperCase() === "GET" ? "params" : "data";
  } else {
    key = "params";
  }
  return instance({
    method: option.method || "get",
    url: option.url,
    [key]: option.data,
  });
};
